package com.iven.xie.sonwflake.service.impl;

import com.iven.xie.sonwflake.beans.ID;
import com.iven.xie.sonwflake.service.IdConverter;
import com.iven.xie.sonwflake.utils.SnowflakeUtils;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author iven.xie
 */
@Data
@NoArgsConstructor
public class IdConverterImpl implements IdConverter {
    @Override
    public long convert(ID id) {
        long ret = 0;

        ret |= id.getSequence();

        ret |= id.getWorker() << SnowflakeUtils.WORK_LEFT_BIT;

        ret |= id.getData() << SnowflakeUtils.DATA_LEFT_BIT;

        ret |= id.getTimeStamp() << SnowflakeUtils.TIME_LEFT_BIT;

        return ret;
    }

    @Override
    public ID convert(long id) {
        ID ret = new ID();

        ret.setSequence(id & SnowflakeUtils.getSeqMaxNum());

        ret.setWorker((id >>> SnowflakeUtils.WORK_LEFT_BIT) & SnowflakeUtils.WORK_MAX_NUM);

        ret.setData((id >>> SnowflakeUtils.DATA_LEFT_BIT) & SnowflakeUtils.DATA_MAX_NUM);

        ret.setTimeStamp((id >>> SnowflakeUtils.TIME_LEFT_BIT) & SnowflakeUtils.TIMESTAMP_MAX_NUM);

        return ret;
    }
}
